package com.tjetc.controller;

import com.tjetc.domain.User;
import com.tjetc.service.UserService;
import com.tjetc.utils.AliOssUtil;
import com.tjetc.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
* (user)表控制层
*
* @author xxxxx
*/
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
/**
* 服务对象
*/
@Resource
private UserService userService;
@Autowired
private AliOssUtil aliOssUtil;

    @GetMapping("importAll")
    public Boolean importAll() {
        return userService.importAll();
    }

    @PostMapping("verifyCode")
    public Result login(@RequestBody User user) {
        System.out.println("user = " + user);
        return userService.verifyCode(user.getPhone());
    }

    @PostMapping("login")
    public Result verifyCode(@RequestBody Map<String, String> request) {
        System.out.println(request.get("phone"));
        System.out.println(request.get("code"));
        return userService.login(request.get("phone"), request.get("code"));
    }

    @PostMapping("/register")
    public Result register(
            @RequestParam("phone") String phone,
            @RequestParam("birthday") String birthday,
            @RequestParam(value = "sex", required = false) String sex,
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "avatar", required = false) MultipartFile avatarFile) {

        try {
            System.out.println("phone = " + phone);
            System.out.println("birthday = " + birthday);
            System.out.println("sex = " + sex);
            System.out.println("username = " + username);
            // 处理头像上传
            String avatarUrl = "/static/default-avatar.jpg";
            if (avatarFile != null && !avatarFile.isEmpty()) {
                String fileName = "avatars/" + UUID.randomUUID() +
                        avatarFile.getOriginalFilename().substring(avatarFile.getOriginalFilename().lastIndexOf("."));
                avatarUrl = aliOssUtil.upload(avatarFile.getBytes(), fileName);
            }

            // 构建用户对象
            User user = new User();
            user.setPhone(phone);
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
            user.setSex(sex != null ? sex : "unknown");
            user.setUsername(username != null ? username : "用户" + System.currentTimeMillis());
            user.setIcon(avatarUrl);
            System.out.println("user = " + user);



            return userService.register(user);
        } catch (Exception e) {
            return Result.fail("注册失败: " + e.getMessage());
        }
    }
}
